package com.xmut.rc.common.utils;

import com.xmut.rc.entity.SysPermission;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 小宋
 * @Version v1.0
 * @ClassName: PermissionUtil
 * @Description:
 * @Date: 2021/12/1 8:30
 */
public class PermissionUtil {

    public static List<SysPermission> getLevelPermission(List<SysPermission> permissionHashSet) {
        if (permissionHashSet.size() > 0) {
            //过滤出一级权限菜单
            List<SysPermission> level1PermissionList = permissionHashSet.stream().filter(item -> "0".equals(item.getParentId())).collect(Collectors.toList());
            for (SysPermission level1Permission : level1PermissionList) {
                //设置权限菜单等级
                level1Permission.setLevel(1);
                //进入封装层级子菜单
                level1Permission.setChildren(getChildrenPermission(level1Permission, permissionHashSet));
            }
            return level1PermissionList;
        }
        return null;
    }

    //设置子节点
    private static List<SysPermission> getChildrenPermission(SysPermission parentPermission, List<SysPermission> permissionHashSet) {
        List<SysPermission> childrenPermission = new ArrayList<>();
        for (SysPermission sysPermission : permissionHashSet) {
            //找到parentPermission的子节点
            if (sysPermission.getParentId().equals(parentPermission.getId())) {
                //设置等级
                sysPermission.setLevel(parentPermission.getLevel() + 1);
                //加入子节点集合，就是parentPermission的子节点集合
                childrenPermission.add(sysPermission);
            }
        }
        if (childrenPermission.size() > 0) {
            //存在子节点，设置子节点
            parentPermission.setChildren(childrenPermission);
            //递归封装，子节点可能有子子节点
            for (SysPermission sysPermission : childrenPermission) {
                getChildrenPermission(sysPermission, permissionHashSet);
            }
        }
        return childrenPermission;
    }
}
